# @Time : 2021/6/18 21:22
# @Author : Li Kunlun
# @Description : Numpy Torch的对比

import torch
import numpy as np

print("---------1、Torch 中Numpy Torch转换--------------------")
np_data = np.arange(6).reshape((2, 3))
# Tensor与Numpy的array还可以进行互相转换，有专门的转换函数
torch_data = torch.from_numpy(np_data)
tensor2array = torch_data.numpy()
# numpy array: [[0 1 2]
#  [3 4 5]]
# torch tensor: tensor([[0, 1, 2],
#         [3, 4, 5]], dtype=torch.int32)
# tensor to array: [[0 1 2]
#  [3 4 5]]
print(
    '\nnumpy array:', np_data,  # [[0 1 2], [3 4 5]]
    '\ntorch tensor:', torch_data,  # [torch.LongTensor of size 2x3]
    '\ntensor to array:', tensor2array,  # [[0 1 2], [3 4 5]]
)

print("---------2、Torch 中的数学运算--------------------")
# abs 绝对值计算
data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data)  # 转换成32位浮点 tensor
# abs
# numpy:  [1 2 1 2]
# torch:  tensor([1., 2., 1., 2.])
print(
    '\nabs',
    '\nnumpy: ', np.abs(data),  # [1 2 1 2]
    '\ntorch: ', torch.abs(tensor)  # [1 2 1 2]
)

# sin   三角函数 sin
# sin
# numpy:  [-0.84147098 -0.90929743  0.84147098  0.90929743]
# torch:  tensor([-0.8415, -0.9093,  0.8415,  0.9093])
print(
    '\nsin',
    '\nnumpy: ', np.sin(data),  # [-0.84147098 -0.90929743  0.84147098  0.90929743]
    '\ntorch: ', torch.sin(tensor)  # [-0.8415 -0.9093  0.8415  0.9093]
)

# mean  均值
# mean
# numpy:  0.0
# torch:  tensor(0.)
print(
    '\nmean',
    '\nnumpy: ', np.mean(data),  # 0.0
    '\ntorch: ', torch.mean(tensor)  # 0.0
)

print("---------3、Torch 中的矩阵运算--------------------")
# matrix multiplication 矩阵点乘
data = [[1, 2], [3, 4]]
tensor = torch.FloatTensor(data)  # 转换成32位浮点 tensor
# correct method

# matrix multiplication (matmul)
# numpy:  [[ 7 10]
#  [15 22]]
# torch:  tensor([[ 7., 10.],
#         [15., 22.]])
print(
    '\nmatrix multiplication (matmul)',
    '\nnumpy: ', np.matmul(data, data),
    '\ntorch: ', torch.mm(tensor, tensor)
)

# !!!!  下面是错误的方法
#  报错tensor.dot(tensor)： RuntimeError: 1D tensors expected, but got 2D and 2D tensors
data = np.array(data)
print(
    '\nmatrix multiplication (dot)',
    '\nnumpy: ', data.dot(data),  # [[7, 10], [15, 22]] 在numpy 中可行
    '\ntorch: ', tensor.dot(tensor)  # 报错  视频中讲述的会转换成 [1,2,3,4].dot = 30.0
)
